package com.tyf.bookreader.manager;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tyf.bookreader.constant.RedisConstants;
import com.tyf.bookreader.domain.BrChapter;
import com.tyf.bookreader.domain.BrContent;
import com.tyf.bookreader.dto.ContentDto;
import com.tyf.bookreader.mapper.BrBookMapper;
import com.tyf.bookreader.mapper.BrChapterMapper;
import com.tyf.bookreader.mapper.BrContentMapper;
import com.tyf.bookreader.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @Description TODO
 * @Author shallow
 * @Date 2023/4/2 15:20
 */
@Component
@Slf4j
public class ContentCacheManager {

    @Autowired
    private RedisService redisService;

    @Autowired
    private BrChapterMapper chapterMapper;

    @Autowired
    private BrBookMapper bookMapper;

    @Autowired
    private BrContentMapper contentMapper;

    public ContentDto getContentById(Long chapterId){
        Object contentDto = redisService.hGet(RedisConstants.CHAPTER_CONTENT_CACHE_KEY, String.valueOf(chapterId));
        if(Objects.nonNull(contentDto)){
            return BeanUtil.toBean(contentDto,ContentDto.class);
        }
        BrChapter chapter = chapterMapper.selectById(chapterId);
        String bookName = bookMapper.selectById(chapter.getBookId()).getBookName();
        String content = contentMapper.selectOne(new LambdaQueryWrapper<BrContent>()
                .eq(BrContent::getChapterId,chapterId).eq(BrContent::getDeleted,0)).getContent();
        ContentDto build = ContentDto.builder()
                .bookName(bookName)
                .chapterNum(chapter.getChapterNum())
                .chapterName(chapter.getChapterName())
                .content(content).build();
        redisService.hSet(RedisConstants.CHAPTER_CONTENT_CACHE_KEY,String.valueOf(chapterId),build,RedisConstants.COMMON_CACHE_TIME);
        return build;
    }
}
